package com.example.provider.qiniuyunDemo;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * All rights Reserved, Designed By www.maihaoche.com
 *
 * @Package com.example.provider.qiniuyunDemo
 * @author: 红雪（hongxue@maihaoche.com）
 * @date: 2019/1/25 4:46 PM
 * @Copyright: 2017-2020 www.maihaoche.com Inc. All rights reserved.
 * 注意：本内容仅限于卖好车内部传阅，禁止外泄以及用于其他的商业项目
 */
public class PrivateDemo {

    private static final String accessKey = "fLEC-LbT3c--z6TfdwtXPFuT2SJ6H4q1GMk8FrHK";
    private static final String secretKey = "1RnMit0n19dCsC3arcio0qlgbqh_AFZhJO8l1M1I";
    private static final String privateBucket="hongxueprivate";
    private static final String uploadPath = "/Users/durui/Pictures/";
    private static final String domain = "plvo19s45.bkt.clouddn.com";

    //返回文件下载的链接{此处有问题}
    public static void download() throws UnsupportedEncodingException {
        String fileName = "hongxue.jpg";
        String domainOfBucket = domain;
        String encodedFileName = URLEncoder.encode(fileName, "utf-8");
        String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
        Auth auth = Auth.create(accessKey, secretKey);
        long expireInSeconds = 3600;//1小时，可以自定义链接过期时间

        String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
        System.out.println(finalUrl);
    }


    public static void main(String[] args) throws UnsupportedEncodingException {
        //simpleUpload();
        download();
    }

    public static void simpleUpload(){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);


        //如果是Windows情况下，格式是 D:\\qiniu\\test.png
        String localFilePath = uploadPath+"test.jpg";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = "hongxue.jpg";
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(privateBucket);
        try {
            Response response = uploadManager.put(localFilePath, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }


    }
}
